#ifndef EVENTLOOP_H
#define EVENTLOOP_H

#include <pthread.h>
#include <vector>
#include <memory>
#include <functional>

#include "EPollPoller.h"
#include "Mutex.h"
#include "Channel.h"
#include "TimerQueue.h"
#include "TimeStamp.h"
#include "callbacks.h"

class Channel;

class EventLoop {
public:
    typedef std::function<void()> Functor;

    EventLoop();
    ~EventLoop();

    bool isInLoopThread();

    void assertInLoopThread();

    void loop();

    void quit();

    void updateChannel(Channel* channel);

    void runInLoop(const Functor& cb);
    void queueInLoop(const Functor& cb);

    void runAt(TimeStamp ts, TimerCallback cb);
    void runAfter(double delay, TimerCallback cb);
    void runEvery(double interval, TimerCallback cb);



private:
    void doPendingFunctors();

    void wakeup();

    void handleRead();

    typedef std::vector<Channel*> ChannelList;

    static const int kPollTimeoutMs = 10000;

    pid_t threadId_;
    bool quit_;
    bool callingPendingFunctors_; // 处理pendFunctors中
    int wakeupFd_;
    Channel wakeupChannel_;
    EPollPoller poller_;
    Mutex mutex_;
    std::vector<Functor> pendingFunctors_;
    ChannelList activeChannelList_;
    TimerQueue timerQueue_;
};

#endif